//map.js
//获取应用实例
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';

const app = getApp()
const util = require("../../utils/util.js")

var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk;

Page({
  /** 页面的初始数据 */
  data: {
    // userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    isHide: false,
    islogin:false,

    longitude: 113.324950,
    latitude:23.020670,
    scale:14,
    markers: [],
    markerTxt:false,
    thismarker:{
      shopName:'',
      address:''
    },
    orderId:'',
    isOrder:false
  },
  /** * 生命周期函数--监听页面加载 */
  onLoad: function (options) {
    var that = this;
    qqmapsdk = new QQMapWX({
      key: '6GZBZ-MAQHJ-IYEFX-KFM47-PBU6K-ITBYI' //自己的key秘钥 http://lbs.qq.com/console/mykey.html 在这个网址申请
    });
    // 登录  如没有则调用wxLogin获取code
    wx.login({
      success: function (res) {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        if (res.code) {
          console.log(res.code)
          // 用户授权登录
          wx.request({
            url: util.getUrl() + 'identity/login',
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            data: { 'code': res.code },
            success: function (res) {
              console.info("login.success",res)
              if (res.data.code == 200) {
                app.globalData.openId = res.data.data.openid;
                app.globalData.userInfo = res.data.data.customer;
                wx.setStorageSync('userInfo', res.data.data.customer);
                // var arr = []
                // arr.push(res.data.data.order)
                // console.log(`data.order arr:`,arr)
                if (res.data.data.order && res.data.data.order.length>0){
                  app.globalData.order = res.data.data.order;
                  var version = res.data.data.device.version;
                  that.setData({
                    isOrder:true
                  })
                  that.toOrder(res.data.data, version)
                }
                that.setData({
                  islogin: true
                });
                app.globalData.islogin = true
              } else if (res.data.code == 401) {
                console.log("401")
                app.globalData.openId = res.data.data.openid;
                // 用户没有授权
                // 改变 isHide 的值，显示授权页面
                wx.showModal({
                  title: '提示',
                  content: '您还未进行登录，小程序内的某些功能将无法正常使用，请问是否去登录？',
                  success(res) {
                    if (res.confirm) {
                      that.setData({
                        isHide: true
                      });
                    } else if (res.cancel) {
                      that.setData({
                        islogin: false
                      });
                      app.globalData.islogin = false                      
                    }
                  }
                })
              }
            }, fail: function (res) {
              console.info("后台接口login.fail:",res)
            },complete:function(res){
              // console.info("后台接口login.complete:", app.globalData)
            }
          })
        }
      }, fail: function (err) {
        console.log('wx.login 接口调用失败，将无法正常使用开放接口等服务', err)
      },complete:function(){
        console.info("wx.login:complete")
      }
    })
    wx.checkSession({
      success: function () { },//session 未过期，并且在本生命周期一直有效
      fail: function () {//登录态过期
        wx.login() //重新登录
      }
    })
    // 判断授权
    if (that.data.isHide == false){
      // 无需申请获取大概地理位置（不精准）
      wx.getSetting({
        success: (res) => {
          if (!res.authSetting['scope.userLocation']) {
            that.mapCtx = wx.createMapContext('map');
            that.mapCtx.getCenterLocation({
              success: function (res) {
                that.setData({
                  longitude: res.longitude,
                  latitude: res.latitude
                })
                that.getLocal(res.latitude, res.longitude)
              }
            })
          }
        }
      })
      that.getLocation();

      //在此函数中获取扫描普通链接二维码参数
      let q = decodeURIComponent(options.q)
      console.log(options.q)
      if (q && q !== 'undefined') {
        app.globalData.codeUrl = q
        var sn = util.getQueryString(q, 'code');
        var version = util.getQueryString(q, 'version');
        var type = util.getQueryString(q, 'type');
        console.log("index 生命周期 onload 参数 sn=" + sn + " version=" + version + " type=" + type)
        wx.showLoading({
          title: '加载中',
          mask:true
        })
        this.timer = setTimeout(() => {
          wx.hideLoading()
          if (that.data.isOrder==false){
            if (version == 3 || type == 3) {
              wx.navigateTo({
                url: '../bluetooth/bluetooth?sn=' + sn + '&region=' + that.data.region + '&city=' + that.data.city,
              })
            } else {
              that.scanCodeAPI(sn, version);
            }
          }
        }, 3000)
      }
      that.nearbyShop();
    }
  },
  // 点击授权
  bindGetUserInfo: function (e) {
    if (e.detail.userInfo) {
      //用户按了允许授权按钮
      var that = this;
      //授权成功后,通过改变 isHide 的值，让实现页面显示出来，把授权页面隐藏起来
      that.setData({
        isHide: false,
        islogin: true
      });
      app.globalData.islogin = true;
      // 无需申请获取大概地理位置（不精准）
      that.mapCtx = wx.createMapContext('map');
      that.mapCtx.getCenterLocation({
        success: function (res) {
          that.setData({
            longitude: res.longitude,
            latitude: res.latitude
          })
        }
      })
      that.getLocation();
      that.nearbyShop();
      app.registered(e.detail.userInfo)
    } else {//用户按了拒绝按钮
      wx.showModal({
        title: '警告',
        content: '您点击了拒绝授权，将无法正常使用小程序，请授权之后再进入!',
        showCancel: false,
        confirmText: '返回授权',
        success: function (res) {
          // 用户没有授权成功，不需要改变 isHide 的值
          if (res.confirm) {
            console.log('用户点击了“返回授权”');
            app.getSetting();
          }
        }
      });
    }
  },
  // 取消授权返回地图
  toback:function(){
    this.setData({
      isHide: false
    });
  },
  // 有订单跳转页面
  toOrder(data, version){
    if (data.order) {
      var order = data.order[0];

      var date1 = new Date()
      var date2 = new Date(order.end)
      var s1 = date1.getTime(), s2 = date2.getTime();
      var time = (s2 - s1) / 1000;

      var day = parseInt(time / (24 * 60 * 60));//计算整数天数
      var afterDay = time - day * 24 * 60 * 60;//取得算出天数后剩余的秒数
      var hour = parseInt(afterDay / (60 * 60));//计算整数小时数
      var afterHour = time - day * 24 * 60 * 60 - hour * 60 * 60;//取得算出小时数后剩余的秒数
      var min = parseInt(afterHour / 60);//计算整数分
      var afterMin = time - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60;
      var timeData = { "days": day, "hours": hour, "minutes": min, "seconds": afterMin, "milliseconds": 0 }

      var pwdMsg = {
        totalTime: order.time,
        time: time * 1000,
        pwd: order.passwd
      }
      var totalTime = order.time;
      var rate = ((totalTime - time) / totalTime) * 100;
      wx.setStorageSync("rate", rate)
      wx.setStorageSync("timeData", timeData)
      console.log(`order:`,order)
      var advertising = app.globalData.swiper || ''
      var bluetoothIDs = ''
      wx.navigateTo({
        url: '../charging/charging?sn=' + order.devicesn + '&pwdMsg=' + JSON.stringify(pwdMsg) + '&orderid=' + order.id + '&advertise=' + JSON.stringify(advertising) + '&version=' + version + '&bluetoothIDs=' + JSON.stringify(bluetoothIDs) + '&shopname=' + order.shop.shopname ,
      })
    }
  },
  // 获取地理位置（精准）
  getLocation:function(){
    var that = this;
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        that.setData({
          longitude: res.longitude,
          latitude: res.latitude
        })
        that.getLocal(res.latitude, res.longitude)
      },
      fail: function () {
        //判断是否获得了用户地理位置授权
        wx.getSetting({
          success: (res) => {
            if (!res.authSetting['scope.userLocation']){
              that.openConfirm()
            } else{
              Toast.fail("请检查您的微信或小程序是否开启定位服务")
            }
          }
        })
      }
    })
  },
  // 获取当前地理位置
  getLocal: function (latitude, longitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        let region = res.result.address_reference.town.title
        let city = res.result.ad_info.city
        vm.setData({
          region: region,
          city:city
        })
        var data = {
          region: region,
          city: city
        }
        app.post('identity/advertising', data).then((res) => {
          if (res.code == 200) {
            app.globalData.swiper = res.list;
            wx.setStorageSync('swiper', res.list);
          }
        }).catch((errMsg) => {
          console.log(errMsg);
        })
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        // console.log(res);
      }
    });
  },
  // 重新申请定位请求
  openConfirm: function () {
    var that = this;
    wx.showModal({
      content: '共城宝定位需要您的地理位置',
      confirmText: "去开启",
      cancelText: "取消",
      success: function (res) {
        //点击“确认”时打开设置页面
        if (res.confirm) {
          wx.openSetting({
            success: (res) => {
              wx.getLocation({
                type: 'gcj02',
                success: function (res) {
                  that.setData({
                    longitude: res.longitude,
                    latitude: res.latitude
                  })
                  that.getLocal(res.latitude, res.longitude)
                }
              })
            }, fail(res) {
              Toast.fail("请检查您的微信或小程序是否开启定位服务")
            }
          })
        } 
        if(res.cancel) {
          that.mapCtx = wx.createMapContext('map');
          that.mapCtx.getCenterLocation({
            success: function (res) {
              that.setData({
                longitude: res.longitude,
                latitude: res.latitude
              })
            }
          })
        }
      }
    });
  },
  // 触发标记点事件
  markertap(e) {
    var that = this;
    var markers = that.data.markers;
    for (var i = 0; i < markers.length;i++){
      if(markers[i].id == e.markerId){
        that.setData({
          markerTxt:true,
          thismarker: markers[i]
        })
      }
    }
    
  },
  // 地图中心位置
  centerpointTap:function(e){
    var that = this;
    if (e.type == "end" && e.causedBy !== 'update') {
      wx.getSetting({
        success: (res) => {
          if (!res.authSetting['scope.userLocation']) {
            that.mapCtx = wx.createMapContext('map');
            that.mapCtx.getCenterLocation({
              success: function (res) {
                that.setData({
                  longitude: res.longitude,
                  latitude: res.latitude
                })
                that.nearbyShop()
              }
            })
          }else{
            that.getLocation();
            that.nearbyShop();
          }
        }
      })
    }else{
      return
    }
  },
  // 回到当前定位点
  backPositioning: function () {
    this.getLocation();
  },
  // 搜索附近的店铺
  nearbyShop: function (){
    var that = this;
    var data = {
      latitude: that.data.latitude,
      longitude: that.data.longitude
    }
    app.post("identity/nearbyShop",data).then((res)=>{
      if (res.code == 200) {
        var markers = [];
        var list = res.list;
        for(var i =0; i<list.length;i++){
          markers.push({
            iconPath: "/resources/location.png",
            width: 30,
            height: 30,
            id: list[i].id,
            latitude: list[i].latitude,
            longitude: list[i].longitude,
            shopName: list[i].shopName,
            address: list[i].address
          })
        }
        that.setData({
          markers: markers
        })
      }
    }).catch((errMsg)=>{
      console.log(errMsg);
    })
 
  },
  // 地图中店铺信息
  maptap:function(){
    this.setData({
      markerTxt:false
    })
  },
  // 扫码
  scanCode:function(){
    var that = this;
    if (app.globalData.islogin==true){
      wx.scanCode({
        scanType: 'qrCode',
        success: function (res) {
          var obj = {};
          let url = res.result;
          app.globalData.codeUrl = url;
          if (url.indexOf("?") != -1) {
            var str = url.split('?')[1];
            var Arr = str.split("&");
            Arr.forEach(function (item) {
              var value = item.split('=')[1];
              var key = item.split('=')[0];
              obj[key] = value;
            })
            var sn = obj['code'];
            var version = obj['version'] || obj['type'];
            if (version == 3) {
              wx.navigateTo({
                url: '../bluetooth/bluetooth?sn=' + sn,
              })
            } else {
              that.scanCodeAPI(sn,version);
            }
          }
        },
        fail: function (res) {
          wx.showToast({
            title: '扫码失败',
          })
        }
      })
    }else{
      wx.showModal({
        title: '提示',
        content: '您还未进行登录，小程序内的某些功能将无法正常使用，请问是否去登录？',
        success(res) {
          if (res.confirm) {
            that.setData({
              isHide: true
            });
          } else if (res.cancel) {
            that.setData({
              islogin: false
            });
            app.globalData.islogin = false;
          }
        }
      })
    }
    
  },
  // 扫码API
  scanCodeAPI: function (sn,version){
    var that = this;
    var data = { sn: sn, region: that.data.region, city:that.data.city };
    app.post('order/menu', data).then((res) => {
      if (res.code == 200) {
        console.log(res)
        if (res.data.advertising !== null){
          app.globalData.swiper = res.data.advertising;
          wx.setStorageSync('swiper', res.data.advertising);
        }
        
        var advertising = res.data.advertising || app.globalData.swiper || ''
        wx.navigateTo({
          url: '../scanPay/scanPay?orderlist=' + JSON.stringify(res.data.product) + '&sn=' + sn + '&advertise=' + JSON.stringify(advertising) + '&shopname=' + res.data.shop.shopname,
        })
      } else if (res.code == 404) {//未激活设备
        console.log(res.message)
        wx.showToast({
          title: res.message,
          icon: 'loading',
          duration: 2000
        })
      } else if (res.code == 500) {
        console.log(res)
        var entity = res.entity;
        if (sn == app.globalData.order[0].devicesn) {
          var data = {
            order: app.globalData.order,
            advertising: app.globalData.swiper
          }
          console.log(`409`, data)
          that.toOrder(data, version)
        }else{
          wx.showModal({
            title: '提示',
            content: '您还有一笔订单没有结束，请问是否结束订单？（结束订单无法再次获取密码或激活设备，但如需获取密码或激活设备需要重新支付生成订单）',
            confirmText: '结束订单',
            success: res => {
              if (res.confirm) {
                that.setData({
                  orderid: entity[0].id
                })
                that.endOrder();
              }
            }
          })
        }
      } else if (res.code == 409) {//设备在使用
        if (app.globalData.order) {
          if (sn == app.globalData.order[0].devicesn) {
            var data = {
              order: app.globalData.order,
              advertising: app.globalData.swiper
            }
            console.log(`409`, data)
            that.toOrder(data, version)
          }
        } else {
          Toast.loading(res.message);
        }
      } else {
        wx.showToast({
          title: '获取失败',
        })
      }
    }).catch((errMsg) => {
      console.log(errMsg);//错误提示信息
    })
  },
  // 结束订单
  endOrder: function () {
    var that = this;
    var orderId = that.data.orderid;
    var data = { id: orderId };
    app.post('order/closeOrder', data).then((res) => {
      if (res.code == 200) {
        Toast('已结束订单，如需充电，请重新扫码支付充电');
      } else {
        console.log(res)
      }
    }).catch((errMsg) => {
      console.log(errMsg);
    })
  },
  // 客服
  serviceTap:function(){
    wx.makePhoneCall({
      phoneNumber: '400-060-2006'
    })
  },
  /*** 用户点击右上角分享*/
  onShareAppMessage: function (res) {
    return {
      title: '共城宝，5G时代服务者，开启智能物联服务',
      path: '/pages/map/map'
    }
  },

  onShow(){
    console.log(app.globalData)
    if(app.globalData.order!==null){
      this.setData({
        isOrder:true
      })
    }else{
      this.setData({
        isOrder:false
      })
    }
    },
  toOrderBtn:function(){
      var data = {
        order: app.globalData.order,
        advertising: app.globalData.swiper
      }
      var version = app.globalData.order[0].device.version;
      console.log(data,version)
      this.toOrder(data, version)
  },

  onUnload() {
    clearTimeout(this.timer)
  }

})